import { login } from "@/apis/administrator/administrator";
import { Administrator, Menu } from "@/apis/administrator/type";
import router from "@/router";
import { defineStore } from "pinia";
import { ref } from "vue";
const modules = import.meta.glob("../views/**/**.vue");
//组合式api写法
//defineStore(唯一标识，函数)

export const useAdminStore = defineStore("admin", () => {
    const token = ref<string | null>("");
    const menus = ref<Menu[]>([]);
    const leftMenus = ref<Menu[]>([]);
    const isRoutesLoaded = ref(false); //是否已经加载路由  注意不能持久化



    const userLogin = async (data: Administrator) => {

        const res = await login(data).catch(()=>undefined);
        if(!res) return false
        token.value = res.data.token;
        menus.value = res.data.menu;

        leftMenus.value= res.data.menu.filter((item:Menu)=>item.pid===0 && item.postion==='left');
        return true;


    }
    //退出登录
    const logout = async () => {

        //删除路由
        // menus.value.forEach(item => {
        //     if(item.url){
        //         let name = item.url.slice(1, 2).toUpperCase() + item.url.slice(2);
        //         router.removeRoute('name)
        //     }
          
        // })
        token.value = null;
        menus.value = [];
        leftMenus.value=[];
        // localStorage.clear();

        location.reload();//刷新页面
    }


    return {
        token,leftMenus,
        menus, userLogin,logout,isRoutesLoaded
    };
}
    , {
        // persist: true //持久化
        persist: {
            key: "user",
            storage: sessionStorage,
            omit: ['isRoutesLoaded'] //isRoutesLoaded不持久
        }
    }
);